//
//  BookMakerImageView.m
//  BookMaker
//
//  Created by Mathieu Tozer on 22/11/07.
//  Copyright 2007 plasq. All rights reserved.
//

#import "BookMakerImageView.h"
#import "BookMakerView.h"
#import "Image.h"
#import "Book.h"
#import "Page.h"
#import "PQMousing.h"

@implementation BookMakerImageView

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
		_pageViews = [[NSMutableArray alloc] init];
		_previousPoint = NSZeroPoint;
		_previousSelection = nil;
    }
    return self;
}

- (void)setUpBindings
{
	[_imagesArayController addObserver:self forKeyPath:@"selection" options:(NSKeyValueObservingOptionNew || NSKeyValueObservingOptionOld) context:NULL];
}

- (void)awakeFromNib
{
	[self setUpBindings];
}

- (void)openImageURL: (NSURL*)url 
{ 
	CGImageRef image = NULL; 
	NSDictionary *mImageProperties = nil;
	CGImageSourceRef isr = CGImageSourceCreateWithURL( (CFURLRef)url, NULL); 
	if (isr) 
	{ 
		image = CGImageSourceCreateImageAtIndex(isr, 0, NULL); 
		if (image) 
		{ 
			mImageProperties = (NSDictionary*)CGImageSourceCopyPropertiesAtIndex( 
																				 isr, 0, (CFDictionaryRef)mImageProperties); 
		} 
		CFRelease(isr); 
	} 
	if (image) 
	{ 
		[self setImage: image 
			 imageProperties: mImageProperties]; 
		CGImageRelease(image); 
	} 
} 

- (Image *)currentImage
{
	NSArray *selection = [_imagesArayController selectedObjects];
	if (selection && [selection count] > 0) {
		return [selection objectAtIndex:0];
	}
	return nil;
}

- (NSArray *)pageObjects
{
	return [[[self currentImage] mutableSetValueForKey:@"pages"] allObjects];
}

- (void)loadPages
{
	NSArray *oldPages = [[self subviews] copy];
	for (NSView *oldPage in oldPages) {
		[oldPage removeFromSuperview];
	}
	
	[_pageViews removeAllObjects];
	NSArray *pages = [self pageObjects];
	for (Page *page in pages) {
		//create a new subview for each and position accordingly, translating the view over the image
		BookMakerView *view = [[BookMakerView alloc] initWithPage:page andView:self];
		[_pageViews addObject:view];
		[self addSubview:view];
	}
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == _imagesArayController && [keyPath isEqualToString:@"selection"]) {
		Image *selection = [self currentImage];
		if (selection) {
			NSString *path = [[selection valueForKey:@"path"] stringByExpandingTildeInPath];
			NSString *escapedString = [[NSString stringWithFormat:@"file://%@", path] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
			NSURL *url = [NSURL URLWithString:escapedString];
			if ([selection isFirstLoad] && _previousSelection) {
				[selection copyPagesFrom:_previousSelection];
			}
			_previousSelection = selection;

			[self openImageURL:url];
			[super zoomImageToFit:self];
			[self loadPages];
		}
	}
	else {
		[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
	}
}

- (IBAction)_zoomImageToFit:(id)sender
{
	[super zoomImageToFit:sender];
	[self loadPages];
}


- (void)shiftMouseDown:(NSEvent *)event
{
	//save the first point, and wait for a second, and then make a new page between the two points.
	if (NSEqualPoints(_previousPoint, NSZeroPoint)) {
		_previousPoint = [self convertViewPointToImagePoint:[self convertPoint:[event locationInWindow] fromView:nil]];
	} else {
//		//form up a new page
//		Image *image = [self currentImage];
//		NSPoint secondPoint = [self convertViewPointToImagePoint:[self convertPoint:[event locationInWindow] fromView:nil]];
//		[image insertNewPageWithRect:NSMakeRect(_previousPoint.x, secondPoint.y, secondPoint.x - _previousPoint.x, _previousPoint.y - secondPoint.y)];
//		_previousPoint = NSZeroPoint;
	//	[self loadPages];
		
		//the user has specified the width, now determine the height for the current book size using the aspect ratio
	//	NSPoint second
		Image *image = [self currentImage];
		NSPoint secondPoint = [self convertViewPointToImagePoint:[self convertPoint:[event locationInWindow] fromView:nil]];
		float width = secondPoint.x - _previousPoint.x;
		float height = width / [(Book *)[image valueForKey:@"book"] effectiveAspectRatio];
		[image insertNewPageWithRect:NSMakeRect(_previousPoint.x, _previousPoint.y - height, width, height)];
		_previousPoint = NSZeroPoint;
		[self loadPages];
	}
}

- (void)mouseDown:(NSEvent *)event
{
	[self dispatchCorrectMousingActionForEvent:event toObject:self];
	[super mouseDown:event];
}

@end
